package com.enbatis.dynamic.datasource.autoconfigure.dialect;

import com.enbatis.dynamic.datasource.autoconfigure.SqlProperty;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * @author wwd
 */
public class C3P0DS {
    private static final Logger log = LoggerFactory.getLogger(C3P0DS.class);

    public static DataSource initC3p0Ds(SqlProperty sqlProperty) {
        ComboPooledDataSource datasource = new ComboPooledDataSource();
        datasource.setJdbcUrl(sqlProperty.getUrl());
        datasource.setUser(sqlProperty.getUsername());
        datasource.setPassword(sqlProperty.getPassword());
        if (StringUtils.isNotBlank(sqlProperty.getInitialSize())) {
            datasource.setInitialPoolSize(Integer.parseInt(sqlProperty.getInitialSize()));
        }

        if (StringUtils.isNotBlank(sqlProperty.getMinIdle())) {
            datasource.setMinPoolSize(Integer.parseInt(sqlProperty.getMinIdle()));
        }
        if (StringUtils.isNotBlank(sqlProperty.getMaxActive())) {
            datasource.setMaxPoolSize(Integer.parseInt(sqlProperty.getMaxActive()));
        }
        try {
            datasource.setDriverClass(sqlProperty.getDriverClassName());
        } catch (PropertyVetoException e) {
            e.printStackTrace();
            log.error("initDruidDs error ", e);
        }
        return datasource;
    }

}
